<template>
  <el-dialog v-model="visible"
             :title="formModel.id?'修改':'新增'"
             width="60%"
             :close-on-click-modal="false"
             draggable>

    <avue-form v-if="visible" ref="avueForm" :option="option" v-model="formModel" @submit="submit"></avue-form>

  </el-dialog>
</template>

<script>

import menuOption from "@/option/sys/menuOption";
import {add, updateRow} from "@/api/sys/menuApi"
import {deepClone} from "utils/util";

const formOption = menuOption();
export default {
  name: "editor",
  computed: {
    option() {
      formOption.emptyBtn = false
      return formOption;
    }
  },
  data() {
    return {
      visible: false,
      formModel: {},
    }
  },
  methods: {
    add(rowId) {
      let row = {}
      if (rowId) {
        row.parentId = rowId;
      }
      row.children = null;
      this.formModel = row;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs.avueForm.init()
      })
    },
    edit(row) {
      if (!row) {
        row = {};
      }
      row = deepClone(row);
      row.children = null;
      this.formModel = row;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs.avueForm.init()
      })
    },
    handleClose() {
      this.visible = false;
      this.formModel = {};
    },

    submit(val, done) {

      val = deepClone(val)
      val.children = null;
      if (!val.parentId || val.parentId.length < 1) {
        val.parentId = 0;
      }
      let fun = val.id ? updateRow : add;

      fun(val).then(res => {
        this.handleClose();
        this.$emit("confirm", val)
      }).finally(() => {
        done();
      })
    }
  }
}
</script>

<style scoped>

</style>
